package com.kevin.mapping.script.engine;

import com.kevin.mapping.script.lexer.Lexer;
import com.kevin.mapping.script.lexer.Token;
import com.kevin.mapping.script.node.stmt.Stmt;
import com.kevin.mapping.script.parser.Parser;

import java.math.BigDecimal;

public class JSONScriptEngine {


    public static Parser parserInstance(Lexer lexer) {
        return new Parser(lexer);
    }

    public static Stmt parser(String expression) {
        Parser parserInstance = parserInstance(new Lexer(expression));
        return parserInstance.parser();
    }

    public static void executeScript(String expression, JSONEnv env) {
        Stmt parser = parser(expression);
        if (null != parser) {
            parser.execute(env);
        }
    }


    public static String getStrValue(String expression, JSONEnv env) {
        Token token = getToken(expression, env);
        if (null == token) {
            return null;
        }
        return token.getStrValue(env);
    }

    public static Double getDoubleValue(String expression, JSONEnv env) {
        Token token = getToken(expression, env);
        if (null == token) {
            return null;
        }
        return token.getDoubleValue(env);
    }

    public static Integer getIntValue(String expression, JSONEnv env) {
        Token token = getToken(expression, env);
        if (null == token) {
            return null;
        }
        return token.getIntValue(env);
    }

    public static Long getLongValue(String expression, JSONEnv env) {
        Token token = getToken(expression, env);
        if (null == token) {
            return null;
        }
        return token.getLongValue(env);
    }

    public static BigDecimal getBigDecimalValue(String expression, JSONEnv env) {
        Token token = getToken(expression, env);
        if (null == token) {
            return null;
        }
        return token.getBigDecimalValue(env);
    }


    public static Object execute(String expression, JSONEnv env) {
        Token token = getToken(expression, env);
        if (null == token) {
            return null;
        }
        return token.getValue(env);
    }

    private static Token getToken(String expression, JSONEnv env) {
        Parser parserInstance = parserInstance(new Lexer(expression));
        Stmt stmt = parserInstance.parser();
        if (null == stmt) {
            return null;
        }
        return stmt.execute(env);
    }
}
